<?php
namespace app\admin\controller;
use think\facade\Db;
use app\admin\model\Demo as DemoModel;
use app\common\BaseController;
use hg\apidoc\annotation as Apidoc;
use think\Request;
use think\exception\ValidateException;
use app\common\support\PHPExcelService;

class Demo extends BaseController{
    

    /**
     * @Apidoc\Title("列表")
     * @Apidoc\Url("Demo_index")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("data", type="array", desc="业务数据",replaceGlobal="true",
     *   @Apidoc\Returned("page",type="int",desc="页码"),
     *   @Apidoc\Returned("limit",type="int",desc="查询数量"),
     *   @Apidoc\Returned("data",type="array",desc="返回数据"),
     *   @Apidoc\Returned("total",type="array",desc="数据总量")
     * )
     */
    public function index(Request $request){
        $page  = (int)$request->param('page/d', 0);
        $limit  = (int)$request->param('limit/d', 10);
        $search = request()->param();
        $where = [];
        if(isset($search["demo_text"]) && $search["demo_text"]!="") $where[] = ["demo_text","=",$search["demo_text"]];
        if(isset($search["demo_select"]) && $search["demo_select"]!="") $where[] = ["demo_select","=",$search["demo_select"]];
        if(isset($search['demo_date']) && $search['demo_date']!="" && is_array($search['demo_date'])){
             $where[] = ["demo_date","between",$search['demo_date']];
        }
        $query  = DemoModel::where($where);
        $total  = $query->count();
        $data   = $query->page($page,$limit)->order('id desc')->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
        ]);
    }

    
        /**
     * @Apidoc\Title ("详情")
     * @Apidoc\Url("Demo_get")
     * @Apidoc\Method("GET")
     * @Apidoc\Param("id", type="int", require=true, desc="id")
     * @Apidoc\Returned("data", type="array", desc="业务数据",replaceGlobal="true",
     *   @Apidoc\Returned("data",type="string",desc="信息")
     * )
     */
    public function detail(int $id): \think\response\Json
    {
        try {
            $row  = DemoModel::where('id', $id)->find();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error($e->getMessage());
        }

        return $this->success('', $row);
    }

    /**
     * @Apidoc\Title("创建")
     * @Apidoc\Url("Demo_create")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("field1", type="string", require=false, desc="field1")
     * @Apidoc\Param("field2", type="string", require=false, desc="field2")
     * @Apidoc\Param("field3", type="string", require=false, desc="field3")
     */
       public function create(Request $request): \think\response\Json
    {
        $data = $request->post();
        try {
            $this->validate($data, [
                //'nickname' => 'require',
            ], [
               // 'nickname.require'  => '昵称必须'
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getError());
        }
        $result = DemoModel::create($data);
        if ($result->isEmpty()) {
            return $this->error('错误');
        }

        return $this->success('成功');
    }



    /**
     * @Apidoc\Title("编辑")
     * @Apidoc\Url("Demo_edit")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("field1", type="string", require=false, desc="field1")
     * @Apidoc\Param("field2", type="string", require=false, desc="field2")
     * @Apidoc\Param("field3", type="string", require=false, desc="field3")
     */
    public function edit(){
        $data = request()->post();
         try {
            $this->validate($data, [
                'id' => 'require',
            ], [
                'id.require'  => '主键必须'
            ]);
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
        if(DemoModel::update($data,['id'=>$data['id']])) return $this->success('操作成功');
        return $this->error('操作失败');
    }





        /**
     * @Apidoc\Title ("删除")
     * @Apidoc\Url("Demo_delete")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("id", type="int", require=true, desc="id")
     */
    public function delete(): \think\response\Json
    {
        $ids = request()->post('ids/s');
        $ids = explode(',', $ids);
        $row = DemoModel::where('id','in', $ids)->select();
        if (!$row) {
            return $this->error('错误');
        }
        $row->delete();
        return $this->success('成功');
    }

    //导出
     public function export_excell(){
        $search = request()->param();
        $where = [];
        if(isset($search["demo_text"]) && $search["demo_text"]!="") $where[] = ["demo_text","=",$search["demo_text"]];
        if(isset($search["demo_number"]) && $search["demo_number"]!="") $where[] = ["demo_number","=",$search["demo_number"]];
        if(isset($search["demo_pass"]) && $search["demo_pass"]!="") $where[] = ["demo_pass","=",$search["demo_pass"]];
        if(isset($search["demo_radio"]) && $search["demo_radio"]!="") $where[] = ["demo_radio","=",$search["demo_radio"]];
        if(isset($search["demo_chekbox"]) && $search["demo_chekbox"]!="") $where[] = ["demo_chekbox","=",$search["demo_chekbox"]];
            if(isset($search["demo_select"]) && $search["demo_select"]!="") $where[] = ["demo_select","=",$search["demo_select"]];
            if(isset($search["demo_selects"]) && $search["demo_selects"]!="") $where[] = ["demo_selects","=",$search["demo_selects"]];
            if(isset($search["demo_pic"]) && $search["demo_pic"]!="") $where[] = ["demo_pic","=",$search["demo_pic"]];
            if(isset($search["demo_pics"]) && $search["demo_pics"]!="") $where[] = ["demo_pics","=",$search["demo_pics"]];
            if(isset($search["demo_video"]) && $search["demo_video"]!="") $where[] = ["demo_video","=",$search["demo_video"]];
            if(isset($search["demo_intro"]) && $search["demo_intro"]!="") $where[] = ["demo_intro","=",$search["demo_intro"]];
            if(isset($search["demo_date"]) && $search["demo_date"]!="") $where[] = ["demo_date","=",$search["demo_date"]];
            if(isset($search["demo_time"]) && $search["demo_time"]!="") $where[] = ["demo_time","=",$search["demo_time"]];
            if(isset($search["damo_range"]) && $search["damo_range"]!="") $where[] = ["damo_range","=",$search["damo_range"]];
            if(isset($search["demo_switch"]) && $search["demo_switch"]!="") $where[] = ["demo_switch","=",$search["demo_switch"]];
            $title = ['编号', 'demo_text','demo_number'];
            set_time_limit(0); // 设置超时时间
            $filename = 'demo导出' . date('Ymdhis') . '.csv';
            header("Content-type:application/vnd.ms-csv");
            header('content-disposition:attachment; filename="' . $filename . '"');
            ob_end_flush();
            // ob_implicit_flush(true);
            // 写入导出标题
            echo iconv('utf-8', 'gbk', implode(',', $title)) . PHP_EOL;
            $lastId = 0;
            while (true) {
                $list =  DemoModel::where($where)->limit(100)->order('id asc')->where('id','>',$lastId)->select()->toArray();
                if (!empty($list)) {
                    foreach ($list as $user) {
                        $item = []; // 初始化数组
                        // 用户信息
                        $item[] = $user['id']; // id
                        $item[] = $user['demo_text']; // 手机号
                        $item[] = $user['demo_number']; // openid
                        // 写入内容
                        echo iconv('utf-8', 'gbk//IGNORE', implode(',', $item)) . PHP_EOL;
                        $lastId = $user['id']; // 最大id
                    }
    
                } else {
                    break;
                }
            }
            exit;  
    }



        /**
     * 导入
     * @return void
     * @author Sam
     */
    public function import_excell(){
        if(empty($_FILES['file'])) json_response(0, '请选择文件');
        $list = big_csv_to_array($_FILES['file']['tmp_name']);
        try{
            $num = 0;
            if(count($list)){
                foreach($list as $k=>$v){
                    $data = [
                        'create_time'=>time(),
                        'update_time'=>time(),
                    ];
                $res =  DemoModel::create($data);
                if($res) $num++;
                }
            }
                return  $this->success('导入成功'.$num.'条数据');
            }catch(\Exception $e){
                return $this->error($e->getMessage());
            }
        }
}